// pages/individual/individual.js
import FormData from '../../utils/formData/index'
import {
  //团队预约模块下载
  findWxDownloadTemplate,
  //预约配置
  HomeList,
  // 获取场次
  findWeekStockByDay,
  //获取手机号
  //团队获取场次
  findTeamWeekStockByDate,
  //校验身份证号
  legitimateIdCard
} from "../../api/home.js";

const {
  globalData
} = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    checked1:"阅读并同意以上内容",
    checked2:"已阅读并同意",
    checked:false,
    closeArr: [],
    show: false,
    ZQindex: 0,
    bulletin: '',
    times: '',
    // 我知道了的倒计时
    otime: 5,
    tabs: [1, 2, 3, 4, 5, 6, 7],
    day: ["一", "二", '三', "四", "五", "六", "日"],
    week: [],
    activeid: '',
    newdata: "",
    //每次切换不同的日期的数据
    meidata: "",
    Ticket: "",
    ex: [],
    //点击切换重新赋值
    newex: [],
    activeids: '',
    teamLimitMax: 0,
    teamLimitMin: 0,
    yonghuLsit: [],
    yonghuArrs: [],
    sessionTime: '',
    travelDate: "",
    delete1: 0,
    teamName: '',
    temporaryClosureSwitch: "",
    teamLeader: '',
    teamCardNum: '',
    downloadUrl: "",
    srcimg: "",
    arrsrc: [],
    idCard: true,
    phone: '',
    faceUrl: "",
    telzzq: '',
    Selecte:'',
    newtime:''
  },
  //预约已满
  buybtn0() {
    wx.showToast({
      title: '预约已满',
      icon: "none"
    })
  },
  //返回上一页
  onClickLeft() {
    wx.navigateBack({
      delta: 1,
    })
  },
  //点击查看预约须知
  onclick() {
    this.setData({
      show: true
    })
  },
  //下载团队预约模块
  biaogemoduluplode() {
    findWxDownloadTemplate().then(res => {
      console.log(res);
      if (res.code == 1000) {
        res.data.map((item) => {
          if (item.templateType == 1) {
            console.log(item);
            this.setData({
              downloadUrl: item.downloadUrl
            })
          }
        })
        wx.navigateTo({
          url: '/pages/download/download?url=' + this.data.downloadUrl,
        })
      } else {
        wx.showModal({
          title: res.data.msg,
        })
      }
    })
  },
  //下载安全承诺书
  downloadanquan() {
    findWxDownloadTemplate().then(res => {
      console.log(res);
      if (res.code == 1000) {
        res.data.map((item) => {
          if (item.templateType == 2) {
            console.log(item);
            this.setData({
              downloadUrl: item.downloadUrl
            })
          }
        })
        wx.navigateTo({
          url: '/pages/download/download?url=' + this.data.downloadUrl,
        })
      } else {
        wx.showModal({
          title: res.data.msg,
        })
      }
    })
  },
  //跳转查看人脸图
  cookLook() {
    wx.navigateTo({
      url: '../Manface/Manface',
    })
  },
  // 轮询展示倒计时的方法
  pollFunc() {
    let omit = this.data.otime

    const timer = setInterval(() => {
      if (omit === 0) {
        clearInterval(this.data.timer)
      }
      this.setData({
        otime: omit--
      })

    }, 1000);
    this.setData({
      show: true
    })

    this.setData({
      timer
    })
  },
  onChange(event){
    this.setData({
        checked: event.detail,
        // checked:true
      });
},
  //点击我知道了
  rightNow() {
    if(this.data.checked == true){
        this.setData({
            show: false
        })
    }else{
       wx.showModal({
           title:"温馨提示",
           content:"请认真阅读以上预约须知内容后，并勾选已阅读同意"
       })
    }
   
},
  //跳转拍照
  gophoto() {
    wx.navigateTo({
      url: '../photo/photo',
    })
  },
  //点击把照片删掉
  xxxx(e) {
    const {
      arrsrc
    } = this.data
    console.log(e.currentTarget.dataset.index);
    const index = e.currentTarget.dataset.index
    this.data.arrsrc[index],
      console.log(this.data.arrsrc[index]);
    wx.showModal({
      title: '确定要删除吗？',
      success: (res) => {
        if (res.confirm) {
          this.data.arrsrc.splice(index, 1)
          this.setData({
            arrsrc
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //点击把照片删掉
  xxxx1(e) {
    wx.showModal({
      title: '确定要删除吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            faceUrl: ''
          })
          wx.setStorageSync('renlianimg', '')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //点击上传安全承诺书
  anquanphoto() {
    let _this = this;
    wx.chooseImage({
      count: 1,
      type: 'image',
      success: (res) => {
        wx.showLoading({
          title: '加载中',
        })
        const {
          arrsrc
        } = this.data
        const tempFilePaths = res.tempFiles
        console.log(tempFilePaths[0].path);
        let formData = new FormData()
        console.log(tempFilePaths[0].path);
        formData.appendFile("file", tempFilePaths[0].path, "test");
        let data = formData.getData()
        console.log(data);
        //    uploadFileq(this.data.src)
        wx.request({
          url: globalData.baseUrl + "/chongqing/api/file/uploadImageFile",
          data: data.buffer,
          header: {
            'content-type': data.contentType,
            appId: "wx9c25f8e317416cd5",
            token: wx.getStorageSync('token')
          },
          method: 'POST',
          timeout: 60000,
          success: (result) => {
            wx.showLoading({
              title: '加载中',
            })
            if (result.data.code == 1000) {
                console.log(result.data.code);
              wx.hideLoading({})
              arrsrc.push(result.data.data)
              console.log(result.data.data);
              this.setData({
                arrsrc
              })
              console.log(this.data.arrsrc);
              wx.hideLoading({})
            } else {
              wx.hideLoading({})
              wx.showModal({
                title: result.data.msg,
              })
            }
          },
          fail: (res) => {
              console.log("失败");
          },
          complete: (res) => {
            console.log("失败22222");

          },
        })
        console.log(this.data.srcimg);
      }
    })
    console.log("666");
  },
  /**
   * 生命周期函数--监听页面加载
   */
  //校验身份证号
  cardNum(e) {
    console.log(e.detail.value);
    if (e.detail.value != "") {
      legitimateIdCard({
        idCard: e.detail.value
      }).then((res) => {
        console.log(res);
        if (res.code == 1000) {
          if (res.data.cardNumFlag == false) {
            this.setData({
              idCard: false
            })
            wx.showToast({
              title: '身份证号有误',
              icon: "none"
            })
          } else {
            this.setData({
              idCard: true
            })
          }
        }
      })
    }
  },
  //校验手机号
  onclicktel(e) {
    console.log(e.detail.value);
    this.setData({
      telzzq: e.detail.value
    })
    const tel = /^((13[0-9])|(14[5-9])|(15([0-3]|[5-9]))|(16[6-7])|(17[1-8])|(18[0-9])|(19[1|3])|(19[5|6])|(19[8|9]))\d{8}$/
    const phone = tel.test(e.detail.value)
    console.log(phone);
    if (e.detail.value != "") {
      if (phone != true) {
        this.setData({
          phone: false
        })
        wx.showToast({
          title: '手机号有误',
          icon: "none"
        })
      } else {
        this.setData({
          phone: true
        })
      }
    }
  },
  // 选择时间段
  activess(e) {
    // console.log(e);
    const index = e.currentTarget.dataset.id
    this.setData({
      activeids: index,
      stockNum: this.data.newex[index].stockNum,
      dayType: this.data.newex[index].dayType
    })
    console.log("点击切换时间并且拿到", this.data.newex[index]);
    this.setData({
      sessionTime: this.data.newex[index].sessionTime
    })
  },
  active(e) {
    const index = e.currentTarget.dataset.id
    var meidatas = this.data.ex[index].travelDate

    //后台设置提前几天
    var date2 = Number(this.data.newtime) * (1000 * 60 * 60 * 24)

    //进来默认选中的
    var date = new Date(this.data.Selecte);
    var time1 = date.getTime();

    // //切换时间的日期
    var date1 = new Date(meidatas);
    var time2 = date1.getTime();
    if (time2 - time1 < date2) {
        wx.showModal({
            title: "温馨提示",
            content: "团队预约需要提前" + this.data.newtime + "天"
        })
        return
    }
    this.setData({
      activeid: index,
      newdata: this.data.ex[index].travelDate.substring(0, 7),
      meidata: this.data.ex[index].travelDate
    })
    //点击切换天的时候把每一天给他传过去
    console.log("切换拿到当天入馆的日期", this.data.ex[index]);
    this.setData({
      travelDate: this.data.ex[index].travelDate
    })
    this.onhelp(this.data.meidata)
  },
  //点击立即预约
  buybtn1() {
    console.log(this.data.faceUrl);
    wx.showLoading({
      title: '加载中',
    })
    if (this.data.newex == '') {
      wx.showToast({
        title: '没有可预约时段',
        icon: "error"
      })
    } else if (this.data.teamName == "") {
      wx.showToast({
        title: '团队名称未填写',
        icon: "error"
      })
    } else if (this.data.teamLeader == "") {
      wx.showToast({
        title: '负责人姓名未填',
        icon: "error"
      })
    } else if (this.data.teamCardNum == "") {
      wx.showToast({
        title: '身份证未填写',
        icon: "error"
      })
    } else if (this.data.phone === "") {
      wx.showToast({
        title: '电话未填写',
        icon: "error"
      })
    } else if (this.data.idCard == false) {
      wx.showToast({
        title: '身份证号有误',
        icon: "none"
      })
    } else if (this.data.phone == false) {
      wx.showToast({
        title: '电话号有误',
        icon: "none"
      })
    } else if (this.data.arrsrc == '') {
      wx.showToast({
        title: '安全承诺书未传',
        icon: "none"
      })
    } else {
      //上传表格

      console.log(this.data.telzzq);
      if (this.data.telzzq != "") {
        const tel = /^((13[0-9])|(14[5-9])|(15([0-3]|[5-9]))|(16[6-7])|(17[1-8])|(18[0-9])|(19[1|3])|(19[5|6])|(19[8|9]))\d{8}$/
        const phone = tel.test(this.data.telzzq)
        console.log(phone);
        if (phone != true) {
          wx.showToast({
            title: '电话号有误',
            icon: "none",
          })
        } else {
          let _this = this
          wx.chooseMessageFile({
            count: 1,
            type: 'file',
            success(res) {
              const tempFilePaths = res.tempFiles
              console.log(tempFilePaths[0].path);
              let formData = new FormData()
              console.log(tempFilePaths[0].path);
              formData.appendFile("file", tempFilePaths[0].path, "test");
              let data = formData.getData()
              console.log(data);
              wx.request({
                url: globalData.baseUrl + "/chongqing/api/reservation/teamImportExcel",
                data: data.buffer,
                header: {
                  'content-type': data.contentType,
                  appId: "wx9c25f8e317416cd5",
                  token: wx.getStorageSync('token')
                },
                method: 'POST',
                timeout: 60000,
                success: (result) => {
                  console.log(result, '我是上传表格888888888888888');
                  wx.showLoading({
                    title: '加载中',
                  })
                  if (result.data.code == 1000) {
                    // console.log(_this.data.sessionTime,"我是入馆时间");
                    // console.log(_this.data.dayType,"我是上午下午");
                    // console.log(_this.data.travelDate,"我是出行日期");
                    // console.log(_this.data.faceUrl,'我是团队人脸');
                    // console.log(_this.data.teamName,"我是团队名称");
                    // console.log(_this.data.teamLeader,'我是团队负责人姓名');
                    // console.log(_this.data.teamCardNum,'我是团队负责任人身份证');
                    // console.log(_this.data.teamPhone,'我是团队负责人手机号');
                    // console.log(_this.data.arrsrc,"我是安全承诺书");
                    result.data.data.infoResultList.forEach((item)=>{
                        for (let index = 0; index < result.data.data.infoResultList.length; index++) {
                            item.id = item.cardNum
                        }
                    })
                    let infoResultList = JSON.stringify(result.data.data.infoResultList)
                    console.log(infoResultList);
                    let emptyUsers = JSON.stringify(result.data.data.emptyUsers)
                    // console.log(emptyUsers);
                    let errorCodes = JSON.stringify(result.data.data.errorCodes)
                    let repeats = JSON.stringify(result.data.data.repeats)
                    // console.log(errorCodes);
                    wx.hideLoading({})
                    wx.navigateTo({
                      url: '/pages/tuanduilist/index?infoResultList=' + infoResultList + '&emptyUsers=' + emptyUsers + '&errorCodes=' + errorCodes + '&sessionTime=' + _this.data.sessionTime + '&dayType=' + _this.data.dayType +
                        '&travelDate=' + _this.data.travelDate + '&faceUrl=' + _this.data.faceUrl + "&teamName=" + _this.data.teamName + '&teamLeader=' + _this.data.teamLeader + '&teamPhone=' + _this.data.teamPhone + "&arrsrc=" + _this.data.arrsrc + '&teamCardNum=' + _this.data.teamCardNum + "&repeats=" +repeats,
                    })
                    console.log(result.data.data);
                  } else {
                    wx.hideLoading({})
                    wx.showModal({
                      title: result.data.msg,
                    })
                  }
                },
                fail: (res) => {},
                complete: (res) => {},
              })
            }
          })
        }

      }

    }
  },

  onhelp(day) {
    findWeekStockByDay({
      bookDate: day
    }).then((res) => {
      console.log(res);
      this.setData({
        newex: res.data.sessionTimes
      })
      //获取每天场次的第一位
      const act = this.data.newex.findIndex(item => !item.sessionTimes)
      if (act > -1) {
        this.setData({
          activeids: act,
        })
      }
      this.setData({
        sessionTime: this.data.newex[act].sessionTime,
        stockNum: this.data.newex[act].stockNum,
        dayType: this.data.newex[act].dayType
      })
    })
  },
  onLoad(options) {
      wx.showLoading({
          title: '加载中',
        })
        this.pollFunc()
    // HomeList().then((res) => {
    //   if (res.code == 1000) {
    //     this.setData({
    //       bulletin: res.data.bulletin
    //     })
    //   } else {
    //     wx.showModal({
    //       title: res.data.msg,
    //     })
    //   }
    // })
    this.setData({
      temporaryClosureSwitch: wx.getStorageSync('temporaryClosureSwitch')
    })
    //进到这个页面要传入的时间
    var a = (new Date().getMonth() + 1) < 10 ? "0" + (new Date().getMonth() + 1) : (new Date().getMonth() + 1)
    var b = new Date().getDate() < 10 ? "0" + new Date().getDate() : new Date().getDate()
    var tiem = new Date().getFullYear() + "-" + a + "-" + b
    let tiemss = tiem.substring(0, 7);
    this.setData({
      times: tiemss
    })

    //获取场次
    //进来请求接口然后拿到 是当天的
    findTeamWeekStockByDate({
      "bookDate": tiem
    }).then((res) => {
      console.log(res, '我是团队预约配置');
      wx.hideLoading({})
      this.setData({
        newtime: res.data.advanceDay,
        teamLimitMax: res.data.teamLimitMax,
        teamLimitMin: res.data.teamLimitMin,
        teamAppointmentSwitch: res.data.teamAppointmentSwitch,
        bulletin: res.data.bulletin
      })
      wx.setStorageSync('teamLimitMin', res.data.teamLimitMin)
      wx.setStorageSync('teamLimitMax', res.data.teamLimitMax)
      //写俩个空数组
      var arr = []
      var arr2 = []
      res.data.oneWeekDateVos.forEach(function (e) {
        arr2.push(e.travelDate.substring(e.travelDate - 2))
        arr.push(e.week)
      })
      var object = this.data.tabs.indexOf(arr[0])
      let a = this.data.day.splice(object, this.data.tabs.length)
      let b = this.data.day.splice(0, object)
      let c = a.concat(b)
      const time = res.data.oneWeekDateVos[res.data.oneWeekDateVos.length - 1].travelDate
      let date = new Date(time)
      const { closeArr } = this.data
      for (let i = 0; i < 7 - res.data.oneWeekDateVos.length; i++) {
        date.setDate(date.getDate() + 1)
        closeArr.push((date.getDate().toString()).padStart(2, '0'))
        console.log(date.getDate())
      }
      console.log(closeArr);
      this.setData({
        week: c,
        ex: res.data.oneWeekDateVos,
        closeArr
      })
      // 寻找到第一个不闭馆的元素
      const active = this.data.ex.findIndex(item => !item.isClose)
      //    如果找到了进行赋值，因为要考虑到是不是都闭馆了
      // console.log(active);
      //id是这个数组得下标对应的
      if (active > -1) {
        this.setData({
          activeid: active,
        })
      }

      console.log("拿到当天入馆的日期", this.data.ex[active]);
      this.setData({
        Selecte: this.data.ex[active].travelDate,
        travelDate: this.data.ex[active].travelDate,
        newdata: this.data.ex[active].travelDate.substring(0, 7),
        //获取每天的场次
        meidata: this.data.ex[active].travelDate
      })
      this.onhelp(this.data.meidata)

    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      faceUrl: wx.getStorageSync('renlianimg')
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // console.log("监听页面卸载");
    wx.setStorageSync('renlianimg', '')
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})